package platform

import (
	"runtime"
	"strings"

	"github.com/aquasecurity/libbpfgo/helpers"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

type ProviderSpec struct {
	// Kernel Version of the platform
	KernelVersion string
	// Syscalls provided by the platform
	Syscalls []string
}

// GenerateSpec generates platform spec where flower run.
func GenerateSpec() (ProviderSpec, error) {
	var err error
	spec := ProviderSpec{}

	if spec.KernelVersion, err = getOSVersion(); err != nil {
		return ProviderSpec{}, err
	}

	if spec.Syscalls, err = syncUpstream(runtime.GOARCH, spec.KernelVersion); err != nil {
		logrus.Warn("get upstream syscalls failed: ", err)
		return spec, nil
	}

	return spec, nil
}

func getOSVersion() (string, error) {
	rawVer, err := helpers.UnameRelease()
	if err != nil {
		return "", errors.Wrap(err, "get kernel version failed with error")
	}

	// Refer to github.com/aquasecurity/libbpfgo@v0.3.0-libbpf-0.8.0/helpers/common.go
	parts := strings.Split(rawVer, "-")  // [base]-xxx
	parts = strings.Split(parts[0], ".") // [major][minor][patch]
	ver := strings.Join(parts[:2], ".")
	logrus.Infof("raw kernel version is: %v, use as: %v", rawVer, ver)

	return ver, nil
}
